import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { isMobile } from '../utils';
import projectManager from '../utils/projectManager';
import globalEventManager, { FILE_EVENTS } from '../utils/eventManager';

// 获取初始状态 - 在模块加载时判断，避免 SSR 问题
const getInitialSidebarState = () => {
  // 如果在服务器端渲染环境，默认关闭
  if (typeof window === 'undefined') {
    return false;
  }
  // 在客户端根据设备类型决定初始状态
  return !isMobile();
};

const useSidebarStore = create(
  persist(
    (set, get) => ({
      // Sidebar 状态
      isOpen: getInitialSidebarState(), // PC端默认打开，移动端默认关闭
      width: 280, // sidebar 宽度
      
      // 文件树状态
      expandedFolders: new Set(), // 展开的文件夹
      selectedFileId: null, // 当前选中的文件
      
      // Actions
      toggleSidebar: () => {
        set((state) => ({ 
          isOpen: !state.isOpen 
        }));
      },
      
      setSidebarOpen: (isOpen) => {
        set({ isOpen });
      },
      
      setSidebarWidth: (width) => {
        // 限制宽度范围
        const constrainedWidth = Math.max(200, Math.min(500, width));
        set({ width: constrainedWidth });
      },
      
      // 文件树操作
      toggleFolder: (folderId) => {
        set((state) => {
          const newExpanded = new Set(state.expandedFolders);
          if (newExpanded.has(folderId)) {
            newExpanded.delete(folderId);
          } else {
            newExpanded.add(folderId);
          }
          return { expandedFolders: newExpanded };
        });
      },
      
      expandFolder: (folderId) => {
        set((state) => ({
          expandedFolders: new Set([...state.expandedFolders, folderId])
        }));
      },
      
      collapseFolder: (folderId) => {
        set((state) => {
          const newExpanded = new Set(state.expandedFolders);
          newExpanded.delete(folderId);
          return { expandedFolders: newExpanded };
        });
      },
      
      setSelectedFile: (fileId) => {
        set({ selectedFileId: fileId });
      },
      
      // 文件操作方法 - 这些方法需要与 projectStore 配合使用
      fileOperations: {
        // 新建文件
        createFile: async (fileName, content = '', parentId = 0) => {
          try {
            const file = await projectManager.createFile(fileName, content, 'python', parentId);
            
            if (file) {
              // 创建成功后，不自动选中新文件，让用户手动点击激活
              // set({ selectedFileId: file.id }); // 移除自动激活逻辑
              
              // 触发文件创建事件
              globalEventManager.emit(FILE_EVENTS.CREATED, { file });
              
              // 通知 projectStore 更新项目状态
              const { useProjectStore } = await import('./index');
              const projectStore = useProjectStore.getState();
              if (projectStore.refreshProject) {
                projectStore.refreshProject();
              }
              
              return { success: true, file };
            } else {
              return { success: false, error: '文件创建失败' };
            }
          } catch (error) {
            console.error('创建文件失败:', error);
            return { success: false, error: error.message || '文件创建失败' };
          }
        },
        
        // 导入文件
        importFile: async (file, targetParentId = null) => {
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            
            reader.onload = async (e) => {
              try {
                const content = e.target?.result;
                if (typeof content === 'string') {
                  // 创建新文件
                  const newFile = await projectManager.createFile(file.name, content, targetParentId);
                  
                  if (newFile) {
                    // 自动选中新文件
                    set({ selectedFileId: newFile.id });
                    
                    // 触发文件创建事件
                    globalEventManager.emit(FILE_EVENTS.CREATED, { file: newFile });
                    
                    // 通知 projectStore 更新项目状态
                    const { useProjectStore } = await import('./index');
                    const projectStore = useProjectStore.getState();
                    if (projectStore.refreshProject) {
                      projectStore.refreshProject();
                    }
                    
                    resolve({ success: true, file: newFile });
                  } else {
                    resolve({ success: false, error: '文件导入失败' });
                  }
                } else {
                  resolve({ success: false, error: '文件内容读取失败' });
                }
              } catch (error) {
                console.error('导入文件失败:', error);
                resolve({ success: false, error: error.message || '文件导入失败' });
              }
            };
            
            reader.onerror = () => {
              resolve({ success: false, error: '文件读取错误' });
            };
            
            // 检查文件大小限制 (10MB)
            if (file.size > 10 * 1024 * 1024) {
              resolve({ success: false, error: '文件大小超过10MB限制' });
              return;
            }
            
            reader.readAsText(file, 'utf-8');
          });
        },
        
        // 新建文件夹
        createFolder: async (folderName, parentId = 0) => {
          try {
            const folder = await projectManager.createFolder(folderName, parentId);
            
            if (folder) {
              // 触发文件夹创建事件
              globalEventManager.emit(FILE_EVENTS.FOLDER_CREATED, { folder });
              
              // 通知 projectStore 更新项目状态
              const { useProjectStore } = await import('./index');
              const projectStore = useProjectStore.getState();
              if (projectStore.refreshProject) {
                projectStore.refreshProject();
              }
              
              return { success: true, folder };
            } else {
              return { success: false, error: '文件夹创建失败' };
            }
          } catch (error) {
            console.error('创建文件夹失败:', error);
            return { success: false, error: error.message || '文件夹创建失败' };
          }
        },
        
        // 删除文件
        deleteFile: async (fileId) => {
          try {
            const result = await projectManager.deleteFile(fileId);
            
            if (result) {
              // 如果删除的是当前选中的文件，清除选中状态
              const currentState = get();
              if (currentState.selectedFileId === fileId) {
                set({ selectedFileId: null });
              }
              
              // 触发文件删除事件
              globalEventManager.emit(FILE_EVENTS.DELETED, { fileId });
              
              // 通知 projectStore 更新项目状态
              const { useProjectStore } = await import('./index');
              const projectStore = useProjectStore.getState();
              if (projectStore.refreshProject) {
                projectStore.refreshProject();
              }
              
              return { success: true };
            } else {
              return { success: false, error: '文件删除失败' };
            }
          } catch (error) {
            console.error('删除文件失败:', error);
            return { success: false, error: error.message || '文件删除失败' };
          }
        },
        
        // 重命名文件
        renameFile: async (fileId, newName) => {
          try {
            // 这里可以添加重命名逻辑
            // 目前先返回未实现
            return { success: false, error: '重命名功能待实现' };
          } catch (error) {
            console.error('重命名文件失败:', error);
            return { success: false, error: error.message };
          }
        }
      },
      
      // 响应式处理
      handleResize: () => {
        const mobile = isMobile();
        const currentState = get();
        
        // 如果切换到移动端且sidebar开启，则关闭它
        if (mobile && currentState.isOpen) {
          set({ isOpen: false });
        }
        // 如果切换到桌面端且sidebar关闭，可以选择性地打开它
        else if (!mobile && !currentState.isOpen) {
          // 这里可以根据用户偏好决定是否自动打开
          // set({ isOpen: true });
        }
      },
      
      // 重置到默认状态
      reset: () => {
        set({
          isOpen: getInitialSidebarState(),
          width: 280,
          expandedFolders: new Set(),
          selectedFileId: null,
        });
      },
      
      // 获取当前状态的便捷方法
      getState: () => get(),
      
      // 检查是否为移动端
      isMobileDevice: () => isMobile(),
    }),
    {
      name: 'python-ide-sidebar-store',
      version: 1,
      partialize: (state) => ({
        isOpen: state.isOpen,
        width: state.width,
        expandedFolders: Array.from(state.expandedFolders), // Set 需要转换为 Array
        selectedFileId: state.selectedFileId,
      }),
      // 反序列化时恢复 Set
      onRehydrateStorage: () => (state) => {
        if (state) {
          state.expandedFolders = new Set(state.expandedFolders || []);
        }
      },
      migrate: (persistedState, version) => {
        if (version < 1) {
          return {
            ...persistedState,
            expandedFolders: new Set(persistedState.expandedFolders || []),
          };
        }
        return persistedState;
      },
    }
  )
);

export default useSidebarStore;
